import React, {useEffect, useState} from 'react';
import {InfoCircleOutlined, UploadOutlined} from '@ant-design/icons';
import type {UploadFile, UploadProps} from 'antd';
import {message as antMessage, Upload} from 'antd';
import {comPlatReq} from "../ComReq";
import {PlatReq} from "../types/CommonTypes";

interface OssDataType {
    success_action_status:"200",
    policy:string,
    "x-oss-signature":string,
    "x-oss-signature-version":"OSS4-HMAC-SHA256",
    "x-oss-credential":string,
    "x-oss-date":string,
    key?:string,//文件名
    dir:string,
    "x-oss-security-token":string
    file?:File,
    expire?: 3600,
    host:string,
}

interface AliyunOSSUploadProps {
    value?: UploadFile[];
    onChange?: (fileList: UploadFile[]) => void;
}

const initOssData = ():Promise<OssDataType> => {
    const req: PlatReq ={
        interfaceName: "gainAliOssUploadPolicy",
        reqData: {
            roleArn:"acs:ram::1710639682380768:role/oss-web-upload",
            bucket:"pufa-ai",
            uploadPrefix:"webUploadResource"
        },
    }
    return new Promise((resolve, reject) => {
        comPlatReq(req)
            .then((data)=>{
                const res = data as Record<string, Record<string, string>>;
                const resp = res.result;
                const ossData: OssDataType={
                    success_action_status:"200",
                    policy:resp.policy,
                    "x-oss-signature":resp.signature,
                    "x-oss-signature-version":"OSS4-HMAC-SHA256",
                    "x-oss-credential":resp.x_oss_credential,
                    "x-oss-date":resp.x_oss_date,
                    dir: resp.dir,
                    "x-oss-security-token":resp.security_token,
                    host:resp.host,
                }
                resolve(ossData);
            })
            .catch((err)=>{reject(err)});
    })
};

const AliyunOSSUpload: React.FC<Readonly<AliyunOSSUploadProps>> = ({ value, onChange }) => {
    const [ossData, setOssData] = useState<OssDataType>();
    const [disabled, setDisabled] = useState(true);
    const init = async () => {
        try {
            const result = await initOssData();
            setOssData(result);
        } catch (err) {
            if (err instanceof Error) {
                antMessage.error(err.message);
            }
        }
    };

    useEffect(() => {
        init().then(()=>{
            setDisabled(false);
        });
    }, []);

    const handleChange: UploadProps['onChange'] = ({ fileList }) => {
        onChange?.([...fileList]);
    };

    const onRemove = (file: UploadFile) => {
        const files = (value || []).filter((v) => v.url !== file.url);
        onChange?.(files);
    };

    const getExtraData: UploadProps['data'] = (file) => ({
        key: file.url,
        success_action_status:ossData?.success_action_status,
        policy:ossData?.policy,
        "x-oss-signature":ossData?.["x-oss-signature"],
        "x-oss-signature-version":ossData?.["x-oss-signature-version"],
        "x-oss-credential":ossData?.["x-oss-credential"],
        "x-oss-date":ossData?.["x-oss-date"],
        "x-oss-security-token":ossData?.["x-oss-security-token"],
    });
    const beforeUpload: UploadProps['beforeUpload'] = async (file) => {
        if (!ossData) {
            return false;
        }
        const expire = Number(ossData.expire) * 1000;
        if (expire < Date.now()) {
            await init();
        }
        const suffix = file.name.slice(file.name.lastIndexOf('.'));
        const filename = Date.now() + suffix;
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        file.url = ossData.dir + filename;
        return file;
    };

    const uploadProps: UploadProps = {
        type:"drag",
        name: 'file',
        multiple: true,
        maxCount:1,
        fileList: value,
        action: ossData?.host,
        onChange: handleChange,
        onRemove,
        data: getExtraData,
        beforeUpload,
    };
    return (
        <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '20px', // 增加组件间距
            padding: '16px', // 添加内边距
            backgroundColor: '#f5f5f5', // 背景色提升层次感
            borderRadius: '8px', // 圆角边框
            boxShadow: '0 2px 4px rgba(0,0,0,0.05)'
        }}>
            <Upload {...uploadProps}
                   disabled={disabled}
                    style={{ width: '120px',height:'50px', textAlign: 'center' }}
                    listType="picture">
                <UploadOutlined style={{ fontSize: '20px', color: '#1890ff' }} />
            </Upload>
            <div style={{
                flex: 1, // 自动填充剩余空间
                color: '#666', // 灰色文字
                fontSize: '14px',
                lineHeight: 1.6, // 行间距优化
                fontStyle: 'italic',
                marginLeft: '20px',
                whiteSpace: 'pre-line' // 保留换行符
            }}><InfoCircleOutlined style={{ color: '#999', marginRight: 4 }} />
                您可以上传PDF、WORD、TXT等文档<br/>
                您也可以上传图片、语音，我们都能识别哦
            </div>
        </div>
    );
};
export default AliyunOSSUpload;